package booksys.Mhome;



import booksys.common.CurrentUser;
import booksys.common.Utils;
import org.apache.ibatis.session.SqlSession;

import java.util.Map;

public class HomeService {
    public void loadCurrentUser(CurrentUser currentUser) {

        SqlSession sess = Utils.openSession();
        try{
            HomeDao dao = sess.getMapper(HomeDao.class);
            Manager manager = dao.findManagerById(currentUser.getUserId());
            sess.commit();

            currentUser.setUserName(manager.getMa_name());
            currentUser.setAvatar(manager.getMa_avatar());
            currentUser.setEmail(manager.getMa_mail());
            currentUser.setPhone(manager.getMa_phone());
            currentUser.setSex(manager.getMa_sex());
            currentUser.setUserId(manager.getMa_id());

        }catch(Exception e){
            sess.rollback();
            throw new RuntimeException("加载用户信息失败！",e);
        }finally {
            sess.close();
        }
    }

    public void setAvatar(CurrentUser currentUser, String filename) {

        SqlSession sess = Utils.openSession();
        try{
            HomeDao dao = sess.getMapper(HomeDao.class);
            dao.updateAvatar(currentUser.getUserId(),filename);
            sess.commit();


        }catch(Exception e){
            sess.rollback();
            throw new RuntimeException("更新头像失败！",e);
        }finally {
            sess.close();
        }
    }

    public void updManager(Map<String,Object> dto) {
        SqlSession sess = Utils.openSession();
        try {
            HomeDao dao = sess.getMapper(HomeDao.class);

            Manager manager = dao.findManagerById(String.valueOf(dto.get("userId")));
            if (manager==null) {
                throw new RuntimeException("没有此用户！");
            }

            dao.updateManager(dto);
            sess.commit();

        } catch (Exception e) {
            e.printStackTrace();
            sess.rollback();
            if (e instanceof RuntimeException) {
                throw e;
            }
            throw new RuntimeException("修改用户信息失败！", e);
        } finally {
            sess.close();
        }
    }

    public void updPassword(Map<String, Object> dto) {
        SqlSession sess = Utils.openSession();
        try {
            HomeDao dao = sess.getMapper(HomeDao.class);

            Manager manager= dao.confirmPassword(dto);
            if (manager==null) {
                throw new RuntimeException("旧密码错误！");
            }

            dao.updatePassword(dto);
            sess.commit();

        } catch (Exception e) {
            e.printStackTrace();
            sess.rollback();
            if (e instanceof RuntimeException) {
                throw e;
            }
            throw new RuntimeException("修改密码失败！", e);
        } finally {
            sess.close();
        }
    }
}
